<template>
  <div class="create-category" id="create-category" @click="handleClick">
    <div class="content">
      <el-icon @click="close"><Close /></el-icon>
      <el-form
        ref="formInstance"
        :model="formData"
        :rules="rules"
      >
        <el-form-item label="相册名称" prop="categoryName">
          <el-input v-model="formData.categoryName" />
        </el-form-item>
        <el-form-item label="相册描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 6 }"
          />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { computed, reactive, Ref, ref } from "vue";
import { useRoute } from "vue-router";
import { saveCategory } from "../../request/category";
import { useImageStore } from "../../store/image";
const imageStore = useImageStore()
const formInstance = ref() as Ref<FormInstance>
const formData = reactive({
  categoryName: '',
  description: ''
})
const rules = reactive<FormRules>({
  categoryName: [
    { required: true, message: '请输入名称', trigger: 'change' },
    { min: 1, max: 10, message: '长度不可以超过10个字符', trigger: 'change' },
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'change' },
    { min: 1, max: 100, message: '长度不可以超过200个字符', trigger: 'change' },
  ],
})
function close(){
  imageStore.categoryCreating = false
}
function submit(){
  formInstance.value.validate(valid => {
    if(valid){
      saveCategory(formData.categoryName, formData.description).then(
        val => {
          imageStore.categories.push(val.data)
          imageStore.categoryCreating = false
          imageStore.categorySelectValue = val.data.id.toString()
          ElMessage({type: 'success', message: '创建成功'})
        }
      )
    }
    else{
      ElMessage({type: 'error', message: '请输入有效的信息'})
    }
  })
  
}
function handleClick(e:any){
  if(e.target.id === 'create-category'){
    close()
  }
}
</script>

<style scoped>

</style>